package com.tywj.buscustomerapp.view.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.tywj.buscustomerapp.Config;
import com.tywj.buscustomerapp.R;
import com.tywj.buscustomerapp.model.bean.ProblemBean;
import com.tywj.buscustomerapp.utils.PhoneUtils;
import com.tywj.buscustomerapp.utils.ToastUtils;
import com.tywj.buscustomerapp.utils.WebServicrUtils;
import com.tywj.buscustomerapp.view.myview.ToastJoe;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class RegisterPwdActivity extends BaseActivity {
    @BindView(R.id.head_left)
    ImageView back;
    @BindView(R.id.head_title)
    TextView title;
    @BindView(R.id.register_edit)
    EditText editText;
    @BindView(R.id.reregister_edit)
    EditText reeditText;
    @BindView(R.id.register_cser)
    EditText editCs;
    @BindView(R.id.getCode) ImageView getCode;
//    @BindView(R.id.phone_number) TextView phoneInfo;
    @BindView(R.id.regetCode) ImageView regetCode;
    @BindView(R.id.register_submit) TextView submit;
    @BindView(R.id.register_call) TextView callPc;

    private String phoneNumber;
    private boolean isHinde = true;
    private boolean isHinde1 = true;


    @Override
    protected int getContentId() {
        return R.layout.activity_register_pwd;
    }

    @Override
    protected void initWidget(Bundle savedInstanceState) {
        super.initWidget(savedInstanceState);
        if (getIntent()!=null){
            phoneNumber = getIntent().getStringExtra("phone");
        }else{
            finish();
        }
        title.setText("设置密码");
    }

    private String getUserId(){
        String onlyString = "";
        try{
            if (Build.VERSION.SDK_INT >= 26) {
                onlyString = PhoneUtils.getid(this);
            }else{
                onlyString = PhoneUtils.getIMid(this);
            }
            if (onlyString!=null && !onlyString.equals("")){
                return  onlyString;
            }
        }catch (Exception e){

        }
        if (onlyString==null || onlyString.equals("")){
            onlyString = PhoneUtils.getAndroidID(this);
        }
        if (onlyString==null || onlyString.equals("")){
            onlyString = PhoneUtils.getSerID(this);
        }
        return onlyString;
    }
    private void doRegister(final String pwd){
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> e){
                try {
                    String uid = getUserId();
                    Log.i("taylor",uid);
                    String channelNumber = editCs.getText().toString();
                    String mes = WebServicrUtils.getInstance().doRegister(phoneNumber,pwd,uid,channelNumber);
                    if (mes.equals("ok")){
                        e.onNext(mes);
                    }else {
                        e.onError(null);
                    }
                } catch (IOException e1) {
                    e.onError(e1);
                    e1.printStackTrace();
                } catch (XmlPullParserException e1) {
                    e.onError(e1);
                    e1.printStackTrace();
                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<String>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(String s) {
                        ToastJoe.getmToastJoe().ToastShowRight(RegisterPwdActivity.this,null,"注册成功");
                        startGet();
                        finish();
                    }

                    @Override
                    public void onError(Throwable e) {
                        ToastJoe.getmToastJoe().ToastShow(RegisterPwdActivity.this,null,"注册失败");
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void startGet(){
        Observable.create(new ObservableOnSubscribe<List<ProblemBean>>() {
            @Override
            public void subscribe(ObservableEmitter<List<ProblemBean>> e){
                try {
                    List<ProblemBean> beans=  WebServicrUtils.getInstance().getActivitys();
                    if (beans!=null && beans.size()>0){
                        e.onNext(beans);
                    }else{
                        e.onError(null);
                    }
                } catch (IOException e1) {
                    e1.printStackTrace();
                    e.onError(null);
                } catch (XmlPullParserException e1) {
                    e1.printStackTrace();
                    e.onError(null);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<ProblemBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(List<ProblemBean> s) {
                        if (s!=null && s.size()>0){
                            if (s.get(0).getIsSend()==1){
                                doSendMessage(s.get(0).getAnswer(),s.get(0).getQuestion());
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void doSendMessage(String url1,String title){
        RequestQueue requestQueue = Volley.newRequestQueue(RegisterPwdActivity.this);
        //创建一个请求
        String url =  "http://sms.cd917.com/api/SmsService/SendSms";
        JSONObject object = new JSONObject();
        try {
            String mes ="【胖哒直通车】最新活动，"+title+"详情请见："+url1;
            object.put("tel",phoneNumber);
            object.put("content",mes);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(url, object, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        });
        //将创建的请求添加到队列中
        requestQueue.add(jsonObjectRequest);
    }

    @Override
    protected void initClick() {
        super.initClick();
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String pwd = editText.getText().toString();
                String repwd = reeditText.getText().toString();
                if (pwd.equals("") || repwd.equals("")){
                    ToastJoe.getmToastJoe().ToastLongShow(RegisterPwdActivity.this,null,"密码不能为空");
                }else if (!pwd.equals(repwd)){
                    ToastJoe.getmToastJoe().ToastLongShow(RegisterPwdActivity.this,null,"两次密码输入不一致，请重新输入");
                    editText.setText("");
                    reeditText.setText("");
                }else{
                    if (pwd!=null && pwd.length()>=8){
                        Observable.create(new ObservableOnSubscribe<String>() {
                            @Override
                            public void subscribe(ObservableEmitter<String> e){
                                try {
                                    String mes = WebServicrUtils.getInstance().doCheckRegister(phoneNumber);
                                    Log.i("taylor",mes);
                                    if (mes.equals("true")){
                                        e.onNext(mes);
                                    }else {
                                        e.onError(null);
                                    }
                                } catch (IOException e1) {
                                    e.onError(e1);
                                    e1.printStackTrace();
                                } catch (XmlPullParserException e1) {
                                    e.onError(e1);
                                    e1.printStackTrace();
                                }
                            }
                        }).subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Observer<String>() {
                                    @Override
                                    public void onSubscribe(Disposable d) {

                                    }

                                    @Override
                                    public void onNext(String s) {
                                        doRegister(pwd);
                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        ToastJoe.getmToastJoe().ToastShow(RegisterPwdActivity.this,null,"此手机号已为注册用户");
                                    }

                                    @Override
                                    public void onComplete() {

                                    }
                                });
                    }else{
                        ToastJoe.getmToastJoe().ToastLongShow(RegisterPwdActivity.this,null,"密码必须为8位以上");
                    }
                }

            }
        });

        callPc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final AlertDialog build = new AlertDialog.Builder(RegisterPwdActivity.this,R.style.AlertDialogStyle).create();
                //自定义布局
                View view = getLayoutInflater().inflate(R.layout.dialog_layout, null);
                build.setView(view, 0, 0, 0, 0);
                build.show();
                //得到当前显示设备的宽度，单位是像素
                int width = getWindowManager().getDefaultDisplay().getWidth();
                //得到这个dialog界面的参数对象
                WindowManager.LayoutParams params = build.getWindow().getAttributes();
                //设置dialog的界面宽度
                params.width = width-(width/3);
                //设置dialog高度为包裹内容
                params.height =  WindowManager.LayoutParams.WRAP_CONTENT;
                //设置dialog的重心
                params.gravity = Gravity.CENTER;
                build.getWindow().setAttributes(params);
                TextView titleTv = view.findViewById(R.id.message);
                TextView messageTv = view.findViewById(R.id.message1);
                titleTv.setText("拨打客服电话");
                final String number = Config.CALL_NUMBER;
                messageTv.setText(number);
                Button btn_sure = view.findViewById(R.id.yes);
                Button btn_cancel = view.findViewById(R.id.no);
                btn_sure.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"+number));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        build.dismiss();
                    }
                });
                btn_cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        build.dismiss();
                    }
                });
            }
        });

        getCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isHinde){
                    isHinde = false;
                    editText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }else{
                    isHinde = true;
                    editText.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                editText.setSelection(editText.getText().toString().length());
            }
        });
        regetCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isHinde1){
                    isHinde1 = false;
                    reeditText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }else{
                    isHinde1 = true;
                    reeditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
                reeditText.setSelection(reeditText.getText().toString().length());
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("注册3");
        MobclickAgent.onResume(this); //统计时长

    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("注册3");
        MobclickAgent.onPause(this);
    }
}
